package servlet;

import org.apache.log4j.Logger;

import src.User;
import src.util.Message;
import src.util.MessageCfg;
import dao.UserDao;

public class LoginController extends NetPlayServlet{

	private Logger log = Logger.getLogger(LoginController.class);
	
	public LoginController()
	{

	}

	public void loginController()
	{
		//handle login check call
		//3 params : 
		// - login
		// - hashPass
		// - ip
				
		String submit_login =  getReq().getParameter("login");
		String submit_pass = getReq().getParameter("pass"); //already crypted
		String submit_ip = getReq().getParameter("ipUser");
					
		new Message( new MessageCfg( true, true));

		Message message = new Message( );
		
		//after checking the profile, we'll store the login/ip couple
		if(checkLogin(submit_login, submit_pass))
		{
			//ok : store profile in database
			//using dao to update profile
			message.setStatus(200);
			message.setStatusInfo("OK");
			send( message.toClient( 200, "User " + submit_login+" logged in successfully"));
			
		}
		else //false : can't login user
		{
			message.setStatus(500);
			message.setStatusInfo("NOK");
			send( message.toClient( 505, "Error : can't login " + submit_login));
		}
		
	}
	

	public boolean checkLogin(String login, String hashPass)
	{
		UserDao dao = new UserDao();
		User u = (User) dao.findByLogin(login);
		
		log.warn("submit : " + login + " " + hashPass);
		log.warn("found : " + u.getLoginUser() + " " + u.getHashPass());
		
		if (u != null && u.getLoginUser().equals(login) && u.getHashPass().equals(hashPass))
			return true;
		else
			return false;
	}
	
}
